Home |
| Latest | About | Random
# My Section 3 Notes. "Getting started: The shortest pieces of C++ Code" The shortest piece of C++ code that would compile and run is: ```cpp int main(){ return 0; } ``` [run](https://cpp.sh/?source=int+main()%0A%7Breturn+0%3B%7D) This code defines a function called `main`, which then returns an `int` of value `0`. Let us save this file as `main.cpp` in some folder. If you compile it, and run it, you will see...nothing! That is, nothing went wrong! For example here I compile `main.cpp` using `g++` compiler, and output `-o` as executable file `main` (which will be `main.exe` in windows, then running `main`: ```cmd > g++ main.cpp -o main > main > ``` Or if you like, use the triangle button "debug and run" in your IDE. Roughly speaking: - A function stores a set of instruction. - When a function runs, it may output a value, in this case the `main` function returns a value `0` to the operating system after it runs. (And often it is not printed in the console.) - When a C++ program runs, it looks for the function called `main` and runs it. So there must be one and exactly one `main` function in a C++ program. - For historical reasons, the return value of a _normally executed_ C++ program is `0`. This is also called an _exit code_. One could use other values to indicate other behaviors. We won't be too concerned with this, however. - The indentation (unlike some other languages) does not matter, nor does the number of spaces. But the semicolon `;` is important! It tells us it is the end of an expression.